package com.cndcare.msc.schedule.task;

import com.cndcare.msc.constants.Constants;
import com.cndcare.msc.service.NettyService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ScheduleTask {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private NettyService nettyService;

    /**
     * 一分钟刷新一次服务器信息
     * @throws Exception
     */
    @Scheduled(cron = "${system.server-cron}")
    @SchedulerLock(name = "refreshServiceInfo", lockAtMostFor = "15", lockAtLeastFor = "15")
    public void refreshServiceInfo() throws Exception {
        List<ServiceInstance> instances = discoveryClient.getInstances("netty-server");
        List<Map<String, Object>> list = new ArrayList<>();
        for (ServiceInstance serviceInstance : instances) {
            String host = serviceInstance.getHost();
            String tcpPort = serviceInstance.getMetadata().get("tcpPort");
            Map<String, Object> map = new HashMap<>();

            map.put("host", host);
            map.put("tcpPort", tcpPort);

            list.add(map);
        }

        log.info("更新服务器: {}", list);
        stringRedisTemplate.opsForValue().set(Constants.NETTY_SERVER_KEY, objectMapper.writeValueAsString(list));
    }

    /**
     * 一分钟刷新一次客户端信息
     * @throws Exception
     */
    @Scheduled(cron = "${system.client-cron}")
    @SchedulerLock(name = "refreshClientInfo", lockAtMostFor = "55", lockAtLeastFor = "55")
    public void refreshClientInfo() {
        log.info("更新客户端");
        nettyService.refreshPc();
    }
}
